<?php
/**
 * 統計画面コントローラー
 *
 * @package  app
 * @extends  Controller
 */
class Controller_Manage_Request extends Controller_Manage {
	private $domain;

	/**
	 * before
	 *
	 * @access  public
	 * @return  Response
	 */
	public function before() {
		parent::before();

		$this -> paths = explode('/', Input::uri());

		if (!empty($_SERVER["HTTPS"])) {
			$this -> domain = 'https://';
		} else {
			$this -> domain = 'http://';
		}
		$this -> domain .= $_SERVER["HTTP_HOST"];
	}

	/**
	 * index
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_index() {
		return Response::forge(View::forge('manage/request/index'), D_HTTP_UPDATE);
	}

	/**
	 * リクエスト一覧
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_list() {
		$description = "";
		$post = Input::post();

		$query = DB::select(DB::expr('request_id AS id'), DB::expr("DATE_FORMAT(create_date,'%Y/%m/%d') AS リクエスト日"), DB::expr('member_id AS 会員ID'), DB::expr('SUBSTR(key3,1,10) AS 曲名'), DB::expr('SUBSTR(key4,1,10) AS アーティスト'), 'key5', 'giftcode');
		$query -> from('member_request');
		$query -> where('request_status', 'new');
		$query -> order_by('request_id');
		$query -> limit(1000);
		$list = $query -> execute() -> as_array();
		foreach ($list as $key => $value) {
			$list[$key]['詳細'] = sprintf('%s/manage/request/detail/%d/', $this -> domain, $list[$key]['id']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['リクエストID'] = $value['id'];
		}
		foreach ($list as $key => $value) {
			$list[$key]['iTunes'] = $value['key5'];
			unset($list[$key]['key5']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['ギフト付与'] = sprintf('%s/manage/request/gift/%d/', $this -> domain, $list[$key]['id']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['ギフトコード'] = $value['giftcode'];
			unset($list[$key]['giftcode']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['送信'] = sprintf('%s/manage/request/send/%d/', $this -> domain, $list[$key]['id']);
			unset($list[$key]['id']);
		}

		$csv = Input::get('csv');
		if (empty($csv)) {
			return Response::forge(View::forge('manage/table', array('list' => $list)), D_HTTP_UPDATE);
		} else {
			return Response::forge(View::forge('manage/csv', array('list' => $list)), D_HTTP_UPDATE);
		}
	}

	/**
	 * リクエスト詳細
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_detail() {
		// リクエスト
		$query = DB::select('request_id', 'create_date', 'member_id', DB::expr('key2 AS track_id'), DB::expr('key3 AS artist'), DB::expr('key4 AS song'), DB::expr('key5 AS iTunes'));
		$query -> from('member_request');
		$query -> where('request_id', $this -> paths[3]);
		$result = $query -> execute() -> as_array();
		foreach ($result[0] as $key => $value) {
			$list[] = array('key' => $key, 'value' => $value);
		}

		// iTunes
		$list[] = array('key' => '', 'value' => '以下iTunesの詳細データ');
		$query = DB::select('data');
		$query -> from('itunes_song');
		$query -> where('itunes_track_id', $result[0]['track_id']);
		$result = $query -> execute() -> as_array();
		$data = json_decode($result[0]['data'], true);
		foreach ($data as $key => $value) {
			if (!is_array($value)) {
				$list[] = array('key' => $key, 'value' => $value);
			} else {
				$list[] = array('key' => $key, 'value' => print_r($value, true));
			}
		}

		$csv = Input::get('csv');
		if (empty($csv)) {
			return Response::forge(View::forge('manage/table', array('list' => $list)), D_HTTP_UPDATE);
		} else {
			return Response::forge(View::forge('manage/csv', array('list' => $list)), D_HTTP_UPDATE);
		}
	}

	/**
	 * ギフトコード付与
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_gift() {
		$post = Input::post();

		// 楽曲情報
		$query = DB::select('request_id', 'giftcode', 'key3', 'key4');
		$query -> from('member_request');
		$query -> where('request_id', $this -> paths[3]);
		$result = $query -> execute() -> as_array();
		$views = $result[0];
		
		if (!empty($post['gifturl'])) {
			$code = str_replace(Config::get('itunes_gift'), '', $post['gifturl']);
			$code = explode('&', $code);
			$post['giftcode'] = $code[0];
		}

		if (isset($post['giftcode'])) {
			$views['giftcode'] = $post['giftcode'];
			
			// 確認
			$query = DB::select('request_id');
			$query -> from('member_request');
			$query -> where('giftcode', $views['giftcode']);
			$result = $query -> execute() -> as_array();
			if (count($result) > 0) {
				$views['error'] = 'このギフトコードは付与済みです';
			} else {
				// 付与
				$views['giftcode'] = $post['giftcode'];
				$query = DB::update('member_request');
				$query -> set(array('giftcode' => $views['giftcode']));
				$query -> where('request_id', $views['request_id']);
				$query -> execute();
				$views['message'] = '付与完了';
				return Response::redirect('/manage/request/list/');
			}
		}

		return Response::forge(View::forge('manage/request/gift', $views), D_HTTP_UPDATE);
	}

	/**
	 * 送信処理
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_send() {
		$post = Input::post();

		// 楽曲情報
		$query = DB::select('request_id', 'member_id', 'giftcode', 'key3', 'key4');
		$query -> from('member_request');
		$query -> where('request_id', $this -> paths[3]);
		$result = $query -> execute() -> as_array();
		$views = $result[0];
		
		if (!empty($post['gifturl'])) {
			$code = str_replace(Config::get('itunes_gift'), '', $post['gifturl']);
			$code = explode('&', $code);
			$post['giftcode'] = $code[0];
		}

		if (!empty($post['giftcode'])) {
			// 確認
			if ($views['giftcode'] != $post['giftcode']) {
				$views['error'] = 'ギフトコードが一致しません';
			} else {
				$member_id = $views['member_id'];
				$song = $views['key3'];
				
				// 付与
				$query = DB::update('member_request');
				$query -> set(array('request_status' => 'send'));
				$query -> where('request_id',$views['request_id']);
				$query -> where('member_id',$views['member_id']);
				$query -> where('giftcode',$views['giftcode']);
				$query -> execute();
				$views['message'] = '送信完了。';

				// プッシュ通知
				$query = DB::select('devicetoken');
				$query -> from('member_info');
				$query -> where('member_id', $member_id);
				$result = $query -> execute() -> as_array();
				if (!empty($result[0]['devicetoken'])) {
					$token = $result[0]['devicetoken'];
					$message = sprintf("「%s」がダウンロード可能になりました！", mb_substr($song,0,30));
					$messages = array();
					$messages[] = array('token' => $token, 'text' => $message);
					$res = $this->apns_push($messages);
					if( $res === true ) {
						$views['message'] .= 'プッシュ通知を送りました。';
						return Response::redirect('/manage/request/list/');
					} else {
						$views['error'] .= 'プッシュ通知でエラー。';
						print_r($res);
					}
				}

			}
		}

		return Response::forge(View::forge('manage/request/send', $views), D_HTTP_UPDATE);
	}

	/**
	 * リクエスト履歴
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_history() {
		$description = "";
		$post = Input::post();

		$query = DB::select('request_status', DB::expr('request_id AS id'), DB::expr("DATE_FORMAT(create_date,'%Y/%m/%d') AS リクエスト日"), DB::expr('member_id AS 会員ID'), DB::expr('SUBSTR(key3,1,10) AS 曲名'), DB::expr('SUBSTR(key4,1,10) AS アーティスト'), 'key5', 'giftcode');
		$query -> from('member_request');
		$query -> order_by('request_id','desc');
		$query -> limit(1000);
		$list = $query -> execute() -> as_array();
		foreach ($list as $key => $value) {
			$list[$key]['詳細'] = sprintf('%s/manage/request/detail/%d/', $this -> domain, $list[$key]['id']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['リクエストID'] = $value['id'];
		}
		foreach ($list as $key => $value) {
			$list[$key]['iTunes'] = $value['key5'];
			unset($list[$key]['key5']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['ステータス'] = $value['request_status'];
			unset($list[$key]['request_status']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['ギフトコード'] = $value['giftcode'];
			unset($list[$key]['giftcode']);
		}

		$csv = Input::get('csv');
		if (empty($csv)) {
			return Response::forge(View::forge('manage/table', array('list' => $list)), D_HTTP_UPDATE);
		} else {
			return Response::forge(View::forge('manage/csv', array('list' => $list)), D_HTTP_UPDATE);
		}
	}

}
